package com.rzico.order.plugin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.rzico.basics.entity.Product;
import com.rzico.basics.entity.Receiver;
import com.rzico.basics.plugin.jd.JDProductInfo;
import com.rzico.basics.plugin.jd.JDServiceUtils;
import com.rzico.basics.plugin.jd.JDStockInfo;
import com.rzico.basics.service.ProductService;
import com.rzico.basics.service.ReceiverService;
import com.rzico.core.entity.SysMsgPush;
import com.rzico.core.entity.SysPlugin;
import com.rzico.core.service.SysMsgPushService;
import com.rzico.core.service.SysPluginService;
import com.rzico.order.entity.*;
import com.rzico.order.enumx.ShippingStatusEnum;
import com.rzico.order.service.*;
import com.rzico.util.CodeGenerator;
import com.rzico.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
public class JDPluginService {

    @Autowired
    private ProductService productService;

    @Autowired
    private ReceiverService receiverService;

    @Autowired
    private ShippingService shippingService;

    @Autowired
    protected ShippingItemService shippingItemService;

    @Autowired
    protected SysPluginService sysPluginService;

    @Autowired
    private SysMsgPushService sysMsgPushService;

    @Autowired
    private AskforService askforService;

    @Autowired
    private AskforItemService askforItemService;

    @Autowired
    private ReturnService returnService;

    @Autowired
    private ReturnItemService returnItemService;

    /**
     * 1.判断所购商品是否由京东商品,若有，收集所有的京东商品sku
     * 2.刷新token，每个京东sku依次判断商品的可售性，上下架状态，区域限制，区域库存，满足后则可提交订单
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String,Object> checkJDPruduct(Order order, Long enterpriseId, String mchId){
        Map<String,Object> result = new HashMap<String, Object>();
        result.put("returnCode","0000");
        List<Map<String, Object>> skuMapList = new ArrayList<Map<String, Object>>();
        for (OrderItem item : order.getItemList()) {
            if (item.getSn().contains("jd-")) {
                Map<String, Object> skuMap = new HashMap<String, Object>();
                skuMap.put("sku", item.getSn().substring(3, item.getSn().length()));
                skuMap.put("name", item.getName().substring(0, 10));
                skuMap.put("num", item.getQuantity());
                skuMap.put("productId", item.getProductId());
                skuMapList.add(skuMap);
            }
        }
        if (0 < skuMapList.size()) {
            //获取京东授权token
            String token = JDServiceUtils.refrash_token();
            //查询收获地址，再根据收获地址查询京东地址编码
            Receiver receiver = receiverService.findById(order.getReceiverId());
            String address = receiver.getAddress();
            boolean addressCheck = true;//用户收货地址在京东API中的转换结果，默认为true
            Map<String, Object> addressMap = JDServiceUtils.getJDAddressFromAddress(token,address);
            if (addressMap.isEmpty()){
                addressCheck = false;
                result.put("returnCode","0001");//当前售后地址在京东地址接口中查询不到，提示用户当前收获地址不支持配送
                return result;
            }
            String provinceId = addressMap.get("provinceId").toString();//京东一级地址id
            String cityId = addressMap.get("cityId").toString();//京东二级地址id
            String countyId = addressMap.get("countyId").toString();//京东三级地址id
            String townId = null;
            if (addressMap.containsKey("townId")) {
                townId = addressMap.get("townId").toString();//京东四级地址id
            }
            for (Map<String, Object> map : skuMapList) {
                if (!addressCheck) {
                    result.put("returnCode","0001");
                    result.put("returnMsg", "商品：" + map.get("name").toString() + "超出配送范围");
                    break;
                }
                //获取商品信息
                Product product = productService.findById(map.get("productId"));
                result.put("returnDesc",product.getName());//返回商品名称
                JDProductInfo jdp = new JDProductInfo();
                //判断商品上下架状态
                jdp = JDServiceUtils.selectJDProductState(token,map.get("sku").toString());
                if ("0".equals(jdp.getState())) {
                    //将商品下架，并发送消息
                    SysMsgPush sysMsgPush = new SysMsgPush();
                    sysMsgPush.setId(CodeGenerator.getUUID());
                    sysMsgPush.setIsPush(false);
                    sysMsgPush.setMsgLevel(1);
                    sysMsgPush.setMsgType(4);
                    sysMsgPush.setReadStatus("2");
                    sysMsgPush.setPushStatus("0");
                    sysMsgPush.setMchId(mchId);
                    sysMsgPush.setSendDate(new Date());
                    sysMsgPush.setSendUserId("system");
                    sysMsgPush.setSendUserName("admin");
                    sysMsgPush.setReceiveUserName("system");
                    sysMsgPush.setReceiveUserId("yunyin");
                    sysMsgPush.setIsAttac("0");
                    Map<String,Object> content = new HashMap<>();
                    content.put("title", "京东商品上架状态改变");
                    content.put("sku", "jd-" + jdp.getSku());
                    content.put("msg", "下单检验时，商品处于下架状态,不可售卖系统已下架");
                    content.put("supplierName", "京东");
                    sysMsgPush.setMsgKey("msg-jingdongMoudle");
                    sysMsgPush.setMsgContent(JSON.toJSONString(content));
                    sysMsgPush.setMsgTitle(content.get("title").toString());
                    sysMsgPushService.insert(sysMsgPush);
                    product.setIsMarketable(false);
                    productService.updateByPrimaryKey(product);
                    result.put("returnCode","0001");//当前商品已经在京东系统中下架
                    result.put("returnMsg", "商品：" + map.get("name").toString() + "超出配送范围");
                    break;
                }
                //判断商品可售性
                jdp = JDServiceUtils.selectJDProductSaleState(token,map.get("sku").toString());
                if ("0".equals(jdp.getSaleState())) {
                    //将商品下架，并发送消息
                    SysMsgPush sysMsgPush = new SysMsgPush();
                    sysMsgPush.setId(CodeGenerator.getUUID());
                    sysMsgPush.setIsPush(false);
                    sysMsgPush.setMsgLevel(1);
                    sysMsgPush.setMsgType(4);
                    sysMsgPush.setReadStatus("2");
                    sysMsgPush.setPushStatus("0");
                    sysMsgPush.setMchId(mchId);
                    sysMsgPush.setSendDate(new Date());
                    sysMsgPush.setSendUserId("system");
                    sysMsgPush.setSendUserName("admin");
                    sysMsgPush.setReceiveUserName("system");
                    sysMsgPush.setReceiveUserId("yunyin");
                    sysMsgPush.setIsAttac("0");
                    Map<String,Object> content = new HashMap<>();
                    content.put("title", "京东商品可售性改变");
                    content.put("name", jdp.getName());
                    content.put("msg", "每日商品库定时更新，商品处于不可售状态,系统已下架");
                    content.put("supplierName", "京东");
                    sysMsgPush.setMsgKey("msg-jingdongMoudle");
                    sysMsgPush.setMsgContent(JSON.toJSONString(content));
                    sysMsgPush.setMsgTitle(content.get("title").toString());
                    sysMsgPushService.insert(sysMsgPush);
                    product.setIsMarketable(false);
                    productService.updateByPrimaryKey(product);
                    result.put("returnCode","0001");//当前商品已经在京东系统中不可售
                    result.put("returnMsg", "商品：" + map.get("name").toString() + "超出配送范围");
                    break;
                }
                //判断地区是否可配送
                Map<String, Object> areaMap = JDServiceUtils.checkAreaLimit(token,map.get("sku").toString(),provinceId,cityId,countyId,townId);
                if ("true".equals(areaMap.get("isAreaRestrict").toString())) {
                    result.put("returnCode","0001");//当前商品在当前收获地址不支持配送
                    result.put("returnMsg", "商品：" + map.get("name").toString() + "超出配送范围");
                    break;
                }
                //查询地区库存
                Map<String, Object> skuParam = new HashMap<String, Object>();
                skuParam.put("skuId", map.get("sku").toString());
                skuParam.put("num", new BigDecimal(map.get("num").toString()).intValue());//购买商品数量
                String skuNums = "[" + JSON.toJSONString(skuParam) + "]";
                String area = provinceId + "_" + cityId + "_" + countyId;
                JDStockInfo jDStockInfo = JDServiceUtils.getStock(token,skuNums,area);
                if (!"33".equals(jDStockInfo.getStockStateId()) && !"39".equals(jDStockInfo.getStockStateId())
                        && !"40".equals(jDStockInfo.getStockStateId())) {
                    result.put("returnCode","0001");//当前商品在当前收获地址库存不足
                    result.put("returnMsg", "商品：" + map.get("name").toString() + "超出配送范围");
                    break;
                }
            }
        }
        return result;
    }

    /**
     * 根据发货单 提交京东订单
     * @param shipList
     * @param mchId
     */
    public void jdOrderSubmit(List<Shipping> shipList, String mchId){
        Boolean amountEnough = false;//金额是否不足标志
        String remainLimit = "";
        for (Shipping shipping : shipList) {
            if (StringUtils.isNotEmpty(shipping.getTranSn())) {
                continue;
            }
            //根据发货单查询该单下的发货单项
            List<ShippingItem> shippingItemList = shippingItemService.getItemList(shipping.getId());
            //若商品中包含京东商品，判断账号余额是否足够
            Map<String, Object> resultMap = checkJDBalance(shippingItemList);
            if (resultMap.get("returnCode").equals("error")) {
                amountEnough = true;
                remainLimit = resultMap.get("remainLimit").toString();
                continue;
            }
            //提交订单
            submit(shipping.getId(), shippingItemList, mchId);
        }
        if (amountEnough) {
            SysMsgPush sysMsgPush = new SysMsgPush();
            sysMsgPush.setId(CodeGenerator.getUUID());
            sysMsgPush.setIsPush(false);
            sysMsgPush.setMsgLevel(2);
            sysMsgPush.setMsgType(4);
            sysMsgPush.setReadStatus("2");
            sysMsgPush.setPushStatus("0");
            sysMsgPush.setMchId(mchId);
            sysMsgPush.setSendDate(new Date());
            sysMsgPush.setSendUserId("system");
            sysMsgPush.setSendUserName("admin");
            sysMsgPush.setReceiveUserName("system");
            sysMsgPush.setReceiveUserId("yunyin");
            sysMsgPush.setIsAttac("0");
            Map<String,Object> content = new HashMap<>();
            content.put("title", "京东商品提交订单时账户余额不足,请充值");
            content.put("balance", remainLimit);
            sysMsgPush.setMsgKey("msg-jingdongMoudle");
            sysMsgPush.setMsgContent(JSON.toJSONString(content));
            sysMsgPush.setMsgTitle(content.get("title").toString());
            sysMsgPushService.insert(sysMsgPush);
        }
    }

    /**
     * 购买京东商品，下单
     * @param id
     * @param itemList
     * @param muchId
     */
    public void submit(Long id, List<ShippingItem> itemList, String muchId){
        /**
         * 发货时调用京东api下单
         * 1.先判断是否有京东商品
         */
        List<Map<String, Object>> skuList = new ArrayList<Map<String, Object>>();//商品sku信息
        List<Map<String, Object>> priceList = new ArrayList<Map<String, Object>>();//商品价格信息
        String token = JDServiceUtils.refrash_token();
        for (ShippingItem item : itemList) {
            if (item.getSn().contains("jd-")) {
                Map<String, Object> skuMap = new HashMap<String, Object>();
                Map<String, Object> priceMap = new HashMap<String, Object>();
                skuMap.put("skuId", item.getSn().substring(3, item.getSn().length()));
                skuMap.put("num", item.getQuantity());
                skuMap.put("bNeedAnnex", true);
                skuMap.put("bNeedGift", false);
                skuList.add(skuMap);
                priceMap.put("skuId", item.getSn().substring(3, item.getSn().length()));
                JDProductInfo jdp = JDServiceUtils.selectJDProductPrice(token, item.getSn().substring(3, item.getSn().length()));
                priceMap.put("price", jdp.getPrice());
                if (0 != item.getCost().compareTo(new BigDecimal(jdp.getPrice()))) {
                    Product product = productService.findById(item.getProductId());
                    SysMsgPush sysMsgPush = new SysMsgPush();
                    sysMsgPush.setId(CodeGenerator.getUUID());
                    sysMsgPush.setIsPush(false);
                    sysMsgPush.setMsgLevel(1);
                    sysMsgPush.setMsgType(4);
                    sysMsgPush.setReadStatus("2");
                    sysMsgPush.setPushStatus("0");
                    sysMsgPush.setMchId(muchId);
                    sysMsgPush.setSendDate(new Date());
                    sysMsgPush.setSendUserId("system");
                    sysMsgPush.setSendUserName("admin");
                    sysMsgPush.setReceiveUserName("system");
                    sysMsgPush.setReceiveUserId("yunyin");
                    sysMsgPush.setIsAttac("0");
                    Map<String,Object> content = new HashMap<>();
                    content.put("title", "京东商品结算价改变");
                    content.put("sku",product.getSn());
                    content.put("name", product.getName());
                    content.put("msg", "调用京东api提交订单时，结算价由" + product.getCost() + "变为" + jdp.getPrice());
                    content.put("supplierName", "京东");
                    sysMsgPush.setMsgKey("msg-jingdongMoudle");
                    sysMsgPush.setMsgContent(JSON.toJSONString(content));
                    sysMsgPush.setMsgTitle(content.get("title").toString());
                    sysMsgPushService.insert(sysMsgPush);
                }
                priceList.add(priceMap);
            }
        }
        if (0 < skuList.size()) {
            Shipping shipping = shippingService.findById(id);
            SysPlugin sysplugin = sysPluginService.findByPlugin(muchId, "marketJDPlugin");
            String thirdOrder = shipping.getSn();//第三方的订单单号（若用订单号且分批次发，则第三方订单号重复导致提交失败，现由订单号改为发货单号，且系统重存在部分第三方订单号为订单号）
            String sku = JSON.toJSONString(skuList);//sku参数
            String name = shipping.getConsignee();//收获人姓名
            String address = shipping.getAddress();//收货人地址
            Map<String, Object> addressMap = JDServiceUtils.getJDAddressFromAddress(token,address);
            String provinceId = addressMap.get("provinceId").toString();//京东一级地址id
            String cityId = addressMap.get("cityId").toString();//京东二级地址id
            String countyId = addressMap.get("countyId").toString();//京东三级地址id
            String townId = "";//京东四级地址id
            if (addressMap.containsKey("townId")) {
                townId = addressMap.get("townId").toString();
            } else {
                townId = "0";
            }
            String mobile = shipping.getPhone();//收获人联系电话
            String email = sysplugin.getAttribute("email");//公司邮箱
            String companyName = sysplugin.getAttribute("companyName");//发票抬头
            String orderPriceSnap = JSON.toJSONString(priceList);//商增专票收票人姓名品价格信息
            String invoiceName = sysplugin.getAttribute("invoiceName");//收票人姓名
            String invoicePhone = sysplugin.getAttribute("invoicePhone");//收票人电话
            String invoiceProvice = sysplugin.getAttribute("invoiceProvice");//增专票收票人所在省--公司地址-省
            String invoiceCity = sysplugin.getAttribute("invoiceCity");//增专票收票人所在市--公司地址-市
            String invoiceCounty = sysplugin.getAttribute("invoiceCounty");//增专票收票人所在区/县--公司地址-区
            String invoiceAddress = sysplugin.getAttribute("invoiceAddress");//增专票收票人所在地址--公司地址
            String regCode = sysplugin.getAttribute("regCode");//专票资质纳税人识别号
            Map<String, Object> submitOrderParam = new HashMap<String, Object>();
            submitOrderParam.put("token", token);
            submitOrderParam.put("thirdOrder", thirdOrder);
            submitOrderParam.put("sku", sku);
            submitOrderParam.put("name", name);
            submitOrderParam.put("province", provinceId);
            submitOrderParam.put("city", cityId);
            submitOrderParam.put("county", countyId);
            submitOrderParam.put("town", townId);
            submitOrderParam.put("address", address);
            submitOrderParam.put("mobile", mobile);
            submitOrderParam.put("email", email);
            submitOrderParam.put("companyName", companyName);
            submitOrderParam.put("orderPriceSnap", orderPriceSnap);
            submitOrderParam.put("invoiceName", invoiceName);
            submitOrderParam.put("invoicePhone", invoicePhone);
            submitOrderParam.put("invoiceProvice", invoiceProvice);
            submitOrderParam.put("invoiceCity", invoiceCity);
            submitOrderParam.put("invoiceCounty", invoiceCounty);
            submitOrderParam.put("invoiceAddress", invoiceAddress);
            submitOrderParam.put("regCode", regCode);
            /**
             * 调用京东api提交订单，获取京东订单号，并将京东订单号与系统发货单相关联
             */
            Map<String, Object> submitOrderResult = JDServiceUtils.submitOrder(token, submitOrderParam);
            if ("0001".equals(submitOrderResult.get("resultCode"))) {
                String jdOrderId = submitOrderResult.get("jdOrderId").toString();//获取订单号
                shipping.setTranSn(jdOrderId);
                shippingService.updateByPrimaryKey(shipping);
            } else {
                //若下单失败，记录下单失败的返回码
                SysMsgPush sysMsgPush = new SysMsgPush();
                sysMsgPush.setId(CodeGenerator.getUUID());
                sysMsgPush.setIsPush(false);
                sysMsgPush.setMsgLevel(2);
                sysMsgPush.setMsgType(4);
                sysMsgPush.setReadStatus("2");
                sysMsgPush.setPushStatus("0");
                sysMsgPush.setMchId(muchId);
                sysMsgPush.setSendDate(new Date());
                sysMsgPush.setSendUserId("system");
                sysMsgPush.setSendUserName("admin");
                sysMsgPush.setReceiveUserName("system");
                sysMsgPush.setReceiveUserId("yunyin");
                sysMsgPush.setIsAttac("0");
                Map<String,Object> content = new HashMap<>();
                content.put("title", "提交订单失败");
                content.put("resultCode", submitOrderResult.get("resultCode"));
                content.put("msg", "调用京东api提交订单时，系统订单" + shipping.getOrderSn() + "下单失败,提交订单参数报文:" + submitOrderParam);
                content.put("supplierName", "京东");
                sysMsgPush.setMsgKey("msg-jingdongMoudle");
                sysMsgPush.setMsgContent(JSON.toJSONString(content));
                sysMsgPush.setMsgTitle(content.get("title").toString());
                sysMsgPushService.insert(sysMsgPush);
            }
        }
    }

    /**
     * 更新京东商品送货单项的运单号
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateShippingItemTrackno(List<ShippingItem> shippingItemList){
        //第一步，获取京东商品skuId，根据京东商品且无运单号的送货单项Id获取送货单Id及京东父订单号，并一起关联
        List<Map<String, Object>> shipMapList = new ArrayList<Map<String, Object>>();
        for (ShippingItem si : shippingItemList) {
            if (si.getSn().contains("jd-")) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("shipItemmId", si.getId());//送货单项id
                map.put("sku", si.getSn().substring(3, si.getSn().length()));//京东商品sku
                Shipping shipping = shippingService.selectByPrimaryKey(si.getShippingId());
                map.put("pOrderId", shipping.getTranSn());//京东父订单号
                shipMapList.add(map);
            }
        }
        /**
         * 第二步， 根据京东父订单号id查询该订单下每件商品的订单号（京东订单可能会拆单产生子订单，子订单会与每件商品相关联）
         */
        String token = JDServiceUtils.refrash_token();//获取京东授权token
        for (Map<String, Object> shipMap : shipMapList){
            List<Map<String, Object>> orderSkuList = selectJdSkuOrderInfo(token, shipMap.get("pOrderId").toString());
            for (Map<String, Object> orderSkuMap : orderSkuList) {
                //如果京东商品skuId相等，根据获取的订单号查询配送信息设置运单号
                if (String.valueOf(shipMap.get("sku")).equals(String.valueOf(orderSkuMap.get("skuId")))){
                    //根据京东订单号查询配送信息,若京东运单号不为空，则设置运单号
                    Map<String, Object> trackResult = JDServiceUtils.JDOrderTrack(token, orderSkuMap.get("jdOrderId").toString());
                    shipMap.put("subTranSn", orderSkuMap.get("jdOrderId"));//设置子订单好
                    if (trackResult.containsKey("deliveryOrderId")) {
                        shipMap.put("trackingNo", trackResult.get("deliveryOrderId"));
                    }
                }
            }
        }
        /**
         * 第三步，对每个送货单项判断，若运单号不为空则进行更新
         */
        for (Map<String, Object> shipMap : shipMapList) {
            if (shipMap.containsKey("trackingNo")){
                ShippingItem shippingItem = shippingItemService.selectByPrimaryKey(shipMap.get("shipItemmId"));
                shippingItem.setTrackingNo(shipMap.get("trackingNo").toString());
                shippingItem.setSubTranSn(shipMap.get("subTranSn").toString());
                shippingItemService.updateByPrimaryKey(shippingItem);
            }
        }
    }

    /**
      * 判断所有有京东订单号的送货单，若该订单下的所有送货单项均有运单号，则更新为已发货
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateShippingStatus(Long supplierId){
        Map<String,Object> params = new HashMap<>();
        params.put("shippingStatus","1");
        params.put("supplierId",supplierId);
        List<Shipping> shippingList =  shippingService.selectList(params);
        for (Shipping shipping : shippingList) {
            List<ShippingItem> shippingItemList = shippingItemService.getItemList(shipping.getId());
            boolean isSend = true;//是否已发货
            for (ShippingItem s : shippingItemList) {
                if (null == s.getTrackingNo()) {
                    isSend = false;
                }
            }
            if (isSend) {
                shipping.setShippingStatus(ShippingStatusEnum.SHIPPING_STATUS_RECEIVED.getId());
                shipping.setModifyDate(new Date());
                shipping.setDeliveryDate(new Date());//设置发货时间
                shippingService.updateByPrimaryKey(shipping);
            }
        }
    }

    /**
     * 因京东订单可能会拆单，需根据京东订单号查询订单详情，将该订单下的每件商品与订单号相关联
     * 1.根据父订单获取订单详情，判断是否有子订单
     * 2.若无子订单，则将该订单下所有商品sku与父订单号相关联
     * 3.若有子订单，遍历所有子订单集合，将改子订单下的商品sku与该子订单号相关联
     * @param token
     * @param jdOrderId
     * @return
     */
    public List<Map<String, Object>> selectJdSkuOrderInfo(String token, String jdOrderId){
        List<Map<String, Object>> orderSkuList = new ArrayList<Map<String, Object>>();
        Map<String, Object> orderResult = JDServiceUtils.getOrderDetail(token, jdOrderId);
        if (orderResult.containsKey("cOrder")) {
            List<Map> orderList = JSONArray.parseArray(String.valueOf(orderResult.get("cOrder")), Map.class);
            for (Map cOrderMap : orderList) {
                String skuInfo = String.valueOf(cOrderMap.get("sku"));
                List<Map> skuList = JSONArray.parseArray(skuInfo, Map.class);
                for (Map skuMap : skuList) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("jdOrderId", String.valueOf(cOrderMap.get("jdOrderId")));
                    map.put("skuId", String.valueOf(skuMap.get("skuId")));
                    orderSkuList.add(map);
                }
            }
        } else {
            String skuInfo = String.valueOf(orderResult.get("sku"));
            List<Map> skuList = JSONArray.parseArray(skuInfo, Map.class);
            for (Map skuMap : skuList) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("jdOrderId", String.valueOf(orderResult.get("jdOrderId")));
                map.put("skuId", String.valueOf(skuMap.get("skuId")));
                orderSkuList.add(map);
            }
        }
        return orderSkuList;
    }

    /**
     * 检查京东账号余额是否充足，避免金额不足导致下单失败
     * @param shippingItemList
     * @return
     */
    public Map<String, Object> checkJDBalance(List<ShippingItem> shippingItemList) {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("returnCode", "success");
        BigDecimal totalJDProductPrice = new BigDecimal(0);//京东商品总金额
        String token = JDServiceUtils.refrash_token();
        for (ShippingItem item : shippingItemList) {
            if (item.getSn().contains("jd-")) {
                JDProductInfo jdp = JDServiceUtils.selectJDProductPrice(token, item.getSn().substring(3, item.getSn().length()));
                BigDecimal totalPrice = new BigDecimal(jdp.getPrice()).multiply(item.getQuantity());
                totalJDProductPrice = totalJDProductPrice.add(totalPrice);
            }
        }
        String type = "1";//类型，表示查询企业充值的账号余额
        Map<String, Object> resultMap = JDServiceUtils.getBalance(token, "福建望岳VOP", type);
        BigDecimal remainLimit = new BigDecimal(resultMap.get("remainLimit").toString());
        if (0 < totalJDProductPrice.compareTo(remainLimit)) {
            result.put("returnCode", "error");
            result.put("remainLimit", remainLimit);
        }
        return result;
    }

    /**
     * 检查售后单中包含的京东商品是否可申请售后
     * @param id
     * @return
     */
    public List<Map<String, Object>> checkAskfor(Long id){
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        String token = JDServiceUtils.refrash_token();
        //根据申请售后单id去获取京东子订单号及商品sku
        Askfor askfor = askforService.selectByPrimaryKey(id);
        Map<String,Object> shipParams = new HashMap<String, Object>();
        shipParams.put("orderId", askfor.getOrderId());
        List<ShippingItem> shippingItemList = new ArrayList<ShippingItem>();
        //根据供应商id及退货单订单来源id去查询发货单，获取京东父订单id
        List<Shipping> shippingList = shippingService.selectList(shipParams);
        for (Shipping si : shippingList) {
            shippingItemList.addAll(shippingItemService.getItemList(si.getId()));
        }
        List<AskforItem> askforItemList = askforItemService.getItemList(id);
        for (AskforItem afi : askforItemList) {
            if (afi.getSn().contains("jd-")) {
                for (ShippingItem si : shippingItemList) {
                    if (afi.getSn().equals(si.getSn())) {
                        String jdOrderId = si.getSubTranSn();
                        String skuId = afi.getSn().substring(3, afi.getSn().length());
                        Map<String, Object> resultMap = getAfterSaleInfo(token, jdOrderId, skuId);
                        resultMap.put("num", afi.getQuantity());
                        result.add(resultMap);
                    }
                }
            }
        }
        return result;
    }

    /**
     * 查询京东订单售后信息
     * @param token
     * @param jdOrderId
     * @param skuId
     * @return
     */
    public Map<String, Object> getAfterSaleInfo(String token, String jdOrderId, String skuId){
        Map<String, Object> afInfoResultMap = new HashMap<String, Object>();
        String canAfterSaleType = "1";//订单是否可售后
        Map<String, Object> canAfterSaleMap = JDServiceUtils.getAfterSaleInfo(token, jdOrderId, skuId, canAfterSaleType);
        afInfoResultMap.put("skuId", skuId);
        if ("true".equals(canAfterSaleMap.get("success").toString())) {
            afInfoResultMap.put("afterSale", true);//订单下商品可申请售后
            afInfoResultMap.put("afterSaleNum", canAfterSaleMap.get("result"));//订单下商品可申请售后
            String serviceType = "";//所有售后类型
            String serviceTypeName = "";//所有售后类型名称
            String afterSaleServiceType = "2";//订单售后类型
            Map<String, Object> afterSaleServiceMap = JDServiceUtils.getAfterSaleInfo(token, jdOrderId, skuId, afterSaleServiceType);
            List<Map> serviceList = (List<Map>) afterSaleServiceMap.get("ComponentExport");
            for (Map map : serviceList) {
                serviceType += map.get("code").toString() + ";";
                serviceTypeName += map.get("name").toString() + ";";
            }
            afInfoResultMap.put("serviceType", serviceType);
            afInfoResultMap.put("serviceTypeName", serviceTypeName);
            String afterSaleDisType = "3";//订单逆向配送
            String saleDis = "";//所有商品逆向配送类型
            String saleDisName = "";//所有商品逆向配送类型名称
            Map<String, Object> afterSaleDisMap = JDServiceUtils.getAfterSaleInfo(token, jdOrderId, skuId, afterSaleDisType);
            List<Map> saleDisList = (List<Map>) afterSaleDisMap.get("ComponentExport");
            for (Map map : saleDisList) {
                saleDis += map.get("code").toString() + ";";
                saleDisName += map.get("name").toString() + ";";
            }
            afInfoResultMap.put("saleDis", saleDis);
            afInfoResultMap.put("saleDisName", saleDisName);
        } else {
            afInfoResultMap.put("afterSale", false);//订单下商品不可申请售后
        }
        return afInfoResultMap;
    }

    /**
     * 京东商品申请售后服务
     * 第一步，根据已同意的退货申请单，获取该退货申请单的申请单项（商品sku）
     * 第二步，获取消息推送记录，由申请单项中商品sku判断商品是否已申请售后，若已申请，则跳过，未申请售后则进行申请
     * 第三步，根据退货申请单的订单id去查询发货单中订单id相同且供应商为京东的发货单，根据sku向匹配将京东子订单号相关联，并调用京东申请售后接口
     * 第四步，申请售后成功后，因京东API只返回申请结果，根据结果记录消息推送
     * 注（根据京东子订单号去查询京东服务号，再填写发运信息，这样一个商品的申请售后流程完成，这一步由其他需用户填写发运信息后才可操作）
     * @param askforList
     * @param supplierId
     * @param mchId
     */
    public void jdAfterSaleApply(List<Askfor> askforList, Long supplierId, String mchId){
        List<Map<String, Object>> applyList = new ArrayList<Map<String, Object>>();//所有售后申请单
        String token = JDServiceUtils.refrash_token();
        //第一步 与 第二步
        Map<String,Object> applyParams = new HashMap<String, Object>();
        applyParams.put("msgKey", "msg-jingdongMoudle");
        applyParams.put("msgLevel", 3);
        List<Map<String, Object>> applySuccessList = new ArrayList<Map<String, Object>>();//所有售后申请成功消息列表
        List<SysMsgPush> sysMsgPushList = sysMsgPushService.selectList(applyParams);
        for (SysMsgPush sysMsgPush : sysMsgPushList) {
            Map<String, Object> msg = JDServiceUtils.jsonToMap(sysMsgPush.getMsgContent());
            if ("success".equals(msg.get("applyResult").toString())) {
                applySuccessList.add(msg);
            }
        }
        for (Askfor askfor : askforList) {
            List<AskforItem> askforItemList = askforItemService.getItemList(askfor.getId());
            //判断该申请单是否由京东商品
            for (AskforItem askforItem : askforItemList) {
                if (askforItem.getSn().contains("jd-")) {
                    boolean hasApply = false;//是否已申请售后通过
                    for (Map<String, Object> map : applySuccessList) {
                        if (askfor.getId().toString().equals(map.get("askforId").toString()) &&
                            askforItem.getId().toString().equals(map.get("askforItemId").toString()) &&
                            askforItem.getSn().equals(map.get("skuId").toString())) {
                            hasApply = true;
                        }
                    }
                    if (hasApply) {
                        continue;
                    }
                    Map<String,Object> applyMap = new HashMap<String, Object>();
                    applyMap.put("askforId", askfor.getId());
                    applyMap.put("askforItemId", askforItem.getId());
                    String questionDesc = askfor.getReason();//产品问题描述
                    //客户信息
                    String name = askfor.getConsignee();//客户姓名
                    String mobile = askfor.getPhone();//客户电话
                    //取件地址信息与返件地址信息默认去用户在本退货单的地址
                    Map<String, Object> addressMap = JDServiceUtils.getJDAddressFromAddress(token, askfor.getAddress());
                    String provinceId = addressMap.get("provinceId").toString();//京东一级地址id
                    String cityId = addressMap.get("cityId").toString();//京东二级地址id
                    String countyId = addressMap.get("countyId").toString();//京东三级地址id
                    String townId = addressMap.get("townId").toString();//京东四级地址id
                    String pickwareType = "4";//取件方式--由客户发货改为上门取件
                    String pickwareProvince = provinceId;//取件省
                    String pickwareCity = cityId;//取件市
                    String pickwareCounty = countyId;//取件区/县
                    String pickwareVillage = townId;//取件乡镇
                    String pickwareAddress = askfor.getAddress();//取件地址
                    String returnwareType = "10";//返件方式--由第三方配送改为自营配送
                    String returnwareProvince = provinceId;//返件省
                    String returnwareCity = cityId;//返件市
                    String returnwareCounty = countyId;//返件区/县
                    String returnwareVillage = townId;//返件乡镇
                    String returnwareAddress = askfor.getAddress();//返件地址
                    Map<String,Object> shipParams = new HashMap<String, Object>();
                    shipParams.put("supplierId", supplierId);
                    shipParams.put("orderId", askfor.getOrderId());
                    //根据供应商id及退货单订单来源id去查询发货单，获取京东父订单id
                    List<Shipping> shippingList = shippingService.selectList(shipParams);
                    for (Shipping shipping : shippingList) {
                        //若发货单的京东订单号为空，说明此订单并未在京东api上提交订单成功，无需申请售后
                        if (StringUtils.isEmpty(shipping.getTranSn())) {
                            continue;
                        }
                        //根据京东父订单id去查询订单详情，根据获取该订单详情
                        List<ShippingItem> shippingItemList = shippingItemService.getItemList(shipping.getId());
                        for (ShippingItem si : shippingItemList) {
                            if (askforItem.getSn().equals(si.getSn())){
                                applyMap.put("jdOrderId", si.getSubTranSn());
                                applyMap.put("skuId", askforItem.getSn());
                                applyMap.put("skuNum", askforItem.getQuantity());
                                applyMap.put("customerContactName", name);
                                applyMap.put("customerTel", mobile);
                                applyMap.put("customerMobilePhone", mobile);
                                applyMap.put("questionDesc", questionDesc);
                                applyMap.put("pickwareType", pickwareType);
                                applyMap.put("pickwareProvince", pickwareProvince);
                                applyMap.put("pickwareCity", pickwareCity);
                                applyMap.put("pickwareCounty", pickwareCounty);
                                applyMap.put("pickwareVillage", pickwareVillage);
                                applyMap.put("pickwareAddress", pickwareAddress);
                                applyMap.put("returnwareType", returnwareType);
                                applyMap.put("returnwareProvince", returnwareProvince);
                                applyMap.put("returnwareCity", returnwareCity);
                                applyMap.put("returnwareCounty", returnwareCounty);
                                applyMap.put("returnwareVillage", returnwareVillage);
                                applyMap.put("returnwareAddress", returnwareAddress);
                            }
                        }
                    }

                    applyList.add(applyMap);
                }
            }
        }
        Integer customerExpect = 10;//售后类型：退货
        String questionPic = "";//图片
        Boolean isHasPackage = true;//是否有包装
        Integer packageDesc = 10;//包装完整
        for (Map<String, Object> applyMap : applyList) {
            if (!applyMap.containsKey("jdOrderId")) {
                continue;
            }
            applyMap.put("customerExpect", customerExpect);//售后类型：退货
            applyMap.put("questionPic", questionPic);//图片信息
            applyMap.put("isHasPackage", isHasPackage);//是否有包装
            applyMap.put("packageDesc", packageDesc);//包装描述
            //申请售后接口
            Map<String, Object> resultApplyMap = JDServiceUtils.createAfsApply(token, applyMap);
            if ("true".equals(resultApplyMap.get("success").toString())) {
                SysMsgPush sysMsgPush = new SysMsgPush();
                sysMsgPush.setId(CodeGenerator.getUUID());
                sysMsgPush.setIsPush(false);
                sysMsgPush.setMsgLevel(3);
                sysMsgPush.setMsgType(4);
                sysMsgPush.setReadStatus("2");
                sysMsgPush.setPushStatus("0");
                sysMsgPush.setMchId(mchId);
                sysMsgPush.setSendDate(new Date());
                sysMsgPush.setSendUserId("system");
                sysMsgPush.setSendUserName("admin");
                sysMsgPush.setReceiveUserName("system");
                sysMsgPush.setReceiveUserId("yunyin");
                sysMsgPush.setIsAttac("0");
                Map<String,Object> content = new HashMap<>();
                content.put("title", "申请售后成功");
                content.put("orderId", applyMap.get("jdOrDerId"));
                content.put("askforId", applyMap.get("askforId"));
                content.put("askforItemId", applyMap.get("askforItemId"));
                content.put("skuId", applyMap.get("skuId"));
                content.put("applyResult", "success");
                content.put("msg", "京东商品" + applyMap.get("skuId") + "申请售后成功");
                content.put("supplierName", "京东");
                sysMsgPush.setMsgKey("msg-jingdongMoudle");
                sysMsgPush.setMsgContent(JSON.toJSONString(content));
                sysMsgPush.setMsgTitle(content.get("title").toString());
                sysMsgPushService.insert(sysMsgPush);
            } else {
                SysMsgPush sysMsgPush = new SysMsgPush();
                sysMsgPush.setId(CodeGenerator.getUUID());
                sysMsgPush.setIsPush(false);
                sysMsgPush.setMsgLevel(3);
                sysMsgPush.setMsgType(4);
                sysMsgPush.setReadStatus("2");
                sysMsgPush.setPushStatus("0");
                sysMsgPush.setMchId(mchId);
                sysMsgPush.setSendDate(new Date());
                sysMsgPush.setSendUserId("system");
                sysMsgPush.setSendUserName("admin");
                sysMsgPush.setReceiveUserName("system");
                sysMsgPush.setReceiveUserId("yunyin");
                sysMsgPush.setIsAttac("0");
                Map<String,Object> content = new HashMap<>();
                content.put("title", "申请售后出错");
                content.put("orderId", applyMap.get("jdOrDerId"));
                content.put("askforId", applyMap.get("askforId"));
                content.put("askforItemId", applyMap.get("askforItemId"));
                content.put("skuId", applyMap.get("skuId"));
                content.put("applyResult", resultApplyMap.get("resultCode"));
                content.put("msg", "京东商品" + applyMap.get("skuId") + "申请售后出错，请求参数为:" + applyMap);
                content.put("supplierName", "京东");
                sysMsgPush.setMsgKey("msg-jingdongMoudle");
                sysMsgPush.setMsgContent(JSON.toJSONString(content));
                sysMsgPush.setMsgTitle(content.get("title").toString());
                sysMsgPushService.insert(sysMsgPush);
            }
        }
    }

    /**
     * 已申请售后的退货单填写发运信息
     * @param returnList
     * @param supplierId
     * @param mchId
     */
    public void trackApply(List<Return> returnList, Long supplierId, String mchId) {
        String token = JDServiceUtils.refrash_token();
        Integer pageIndex = 1;
        Integer pageSize = 10;
        for (Return re : returnList) {
            Map<String,Object> shipParams = new HashMap<String, Object>();
            shipParams.put("supplierId", supplierId);
            shipParams.put("orderId", re.getOrderId());
            //根据供应商id及退货单订单来源id去查询发货单，获取京东父订单id
            List<Shipping> shippingList = shippingService.selectList(shipParams);
            Long shippingId = shippingList.get(0).getId();//每个退货单对应的送货单id
            //根据京东父订单id去查询订单详情，根据获取该订单详情
            List<ShippingItem> shippingItemList = shippingItemService.getItemList(shippingId);
            List<ReturnItem> returnItemList = returnItemService.getItemList(re.getId());
            for (ReturnItem returnItem : returnItemList) {
                //判断是否已存在服务单，若存在服务单说明已存在服务单，无需再进行申请
                if (StringUtils.isNotEmpty(returnItem.getSubTranSn())) {
                    continue;
                }
                //无运单号不处理
                if (StringUtils.isEmpty(returnItem.getTrackingNo())) {
                    continue;
                }
                String jdOrDerId = "";//京东子订单号
                String afsServiceId = "";//服务单号
                for (ShippingItem si : shippingItemList) {
                    if (returnItem.getSn().equals(si.getSn())){
                        jdOrDerId = si.getSubTranSn();
                        Map<String, Object> resultServiceMap = JDServiceUtils.getServiceListPage(token, jdOrDerId, pageIndex, pageSize);
                        List<Map> list = JSONArray.parseArray(resultServiceMap.get("serviceInfoList").toString(), Map.class);
                        for (Map m : list) {
                            afsServiceId = m.get("afsServiceId").toString();
                        }
                    }
                }
                //在退货单项中记录对应商品的京东服务单号
                returnItem.setSubTranSn(afsServiceId);
                returnItemService.updateByPrimaryKeySelective(returnItem);
                //申请售后时，商品取件方式由客户发货改为上门取件，所以无须填写发运信息，只需更新京东服务单号即可
                /*String freightMoney = "0";
                String deliverDate = DateUtils.getCurrTimeStr(DateUtils.HYPHEN_DISPLAY_DATE);
                String expressCode = returnItem.getTrackingNo();//运单号
                //填写发运信息，调用快递100接口查询快递信息
                Map<String,Object> trackResult = shippingService.deliveryQuery(expressCode);
                String expressCompany = trackResult.get("com").toString();//发运公司
                Map<String, Object> resultUpdateSkuMap = JDServiceUtils.updateSendSku(token, afsServiceId, freightMoney, expressCompany, deliverDate, expressCode);
                //判断发运信息是否填写成功，不成功记录下记录
                if ("true".equals(resultUpdateSkuMap.get("success").toString())) {
                    SysMsgPush sysMsgPush = new SysMsgPush();
                    sysMsgPush.setId(CodeGenerator.getUUID());
                    sysMsgPush.setIsPush(false);
                    sysMsgPush.setMsgLevel(1);
                    sysMsgPush.setMsgType(4);
                    sysMsgPush.setReadStatus("2");
                    sysMsgPush.setPushStatus("0");
                    sysMsgPush.setMchId(mchId);
                    sysMsgPush.setSendDate(new Date());
                    sysMsgPush.setSendUserId("system");
                    sysMsgPush.setSendUserName("admin");
                    sysMsgPush.setReceiveUserName("system");
                    sysMsgPush.setReceiveUserId("yunyin");
                    sysMsgPush.setIsAttac("0");
                    Map<String,Object> content = new HashMap<>();
                    content.put("title", "填写发运信息成功");
                    content.put("orderId", jdOrDerId);
                    content.put("afsServiceId", afsServiceId);
                    content.put("msg", "京东服务单" + afsServiceId + ",商品sku：" + returnItem.getSn().substring(3, returnItem.getSn().length() - 3) + "申请售后成功，填写发运信息成功");
                    content.put("supplierName", "京东");
                    sysMsgPush.setMsgKey("msg-jingdongMoudle");
                    sysMsgPush.setMsgContent(JSON.toJSONString(content));
                    sysMsgPush.setMsgTitle(content.get("title").toString());
                    sysMsgPushService.insert(sysMsgPush);
                } else {
                    SysMsgPush sysMsgPush = new SysMsgPush();
                    sysMsgPush.setId(CodeGenerator.getUUID());
                    sysMsgPush.setIsPush(false);
                    sysMsgPush.setMsgLevel(1);
                    sysMsgPush.setMsgType(4);
                    sysMsgPush.setReadStatus("2");
                    sysMsgPush.setPushStatus("0");
                    sysMsgPush.setMchId(mchId);
                    sysMsgPush.setSendDate(new Date());
                    sysMsgPush.setSendUserId("system");
                    sysMsgPush.setSendUserName("admin");
                    sysMsgPush.setReceiveUserName("system");
                    sysMsgPush.setReceiveUserId("yunyin");
                    sysMsgPush.setIsAttac("0");
                    Map<String,Object> content = new HashMap<>();
                    content.put("title", "填写发运信息出错");
                    content.put("orderId", jdOrDerId);
                    content.put("afsServiceId", afsServiceId);
                    content.put("msg",  "京东服务单" + afsServiceId + ",商品sku：" + returnItem.getSn().substring(3, returnItem.getSn().length() - 3) + "申请售后成功，填写发运信息报错");
                    content.put("supplierName", "京东");
                    sysMsgPush.setMsgKey("msg-jingdongMoudle");
                    sysMsgPush.setMsgContent(JSON.toJSONString(content));
                    sysMsgPush.setMsgTitle(content.get("title").toString());
                    sysMsgPushService.insert(sysMsgPush);
                }*/
            }
        }
    }

    /**
     * 将已申请完的退货单状态更新为已发货，避免重复申请
     * @param returnList
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateReturnStatus(List<Return> returnList) {
        for (Return re : returnList) {
            List<ReturnItem> returnItemList = returnItemService.getItemList(re.getId());
            boolean isSend = true;//是否已退货
            for (ReturnItem reItem : returnItemList) {
                //存在服务单说明已申请过服务，
                if (null == reItem.getSubTranSn()) {
                    isSend = false;
                }
            }
            if (isSend) {
                re.setShippingStatus(2);//已发货？已送达
                returnService.updateByPrimaryKey(re);
            }
        }
    }

}
